<template>
  <div class="abnormal-record-container">
    <div class="page-header">
      <span class="page-title">异常记录管理</span>
    </div>

    <!-- 搜索卡片 -->
    <el-card class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="异常类型">
          <el-input
            placeholder="请输入异常类型"
            v-model="searchForm.abnormalType"
            @keydown.enter="loadAbnormalRecords()"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select
            placeholder="请选择"
            v-model="searchForm.status"
            @change="loadAbnormalRecords()">
            <el-option label="全部" value=""></el-option>
            <el-option label="待处理" value="pending"></el-option>
            <el-option label="已处理" value="processed"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="reset()">重置</el-button>
          <el-button type="primary" @click="loadAbnormalRecords()">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 异常记录列表 -->
    <el-card class="table-card">
      <div class="abnormal-cards">
        <el-card
          v-for="record in filteredRecords"
          :key="record.abnormalId"
          class="abnormal-card">
          <div class="abnormal-header">
            <span class="abnormal-id">记录编号: {{ record.abnormalId }}</span>
            <el-tag
              :type="getProcessingStatus(record.abnormalId) === 'pending' ? 'warning' : 'success'"
              class="status-tag">
              {{ getProcessingStatus(record.abnormalId) === 'pending' ? '待处理' : '已处理' }}
            </el-tag>
          </div>

          <div class="abnormal-content">
            <div class="abnormal-item">
              <label>异常类型:</label>
              <span>{{ record.abnormalType }}</span>
            </div>

            <div class="abnormal-item">
              <label>异常原因:</label>
              <span>{{ record.reason }}</span>
            </div>

            <div class="abnormal-item">
              <label>记录时间:</label>
              <span>{{ formatDateTime(record.createdAt) }}</span>
            </div>
          </div>

          <div class="abnormal-footer">
            <el-button type="primary" link @click="viewAbnormalRecord(record)">
              查看详情
            </el-button>
          </div>
        </el-card>
      </div>
      <div>
        <!--分页-->
        <el-empty v-if="abnormalRecords.length === 0 && !loading" description="暂无数据" />
        <el-pagination
            v-show="abnormalRecords.length > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="searchForm.pageNum"
            :page-sizes="[4, 8, 10 , 20]"
            :page-size="searchForm.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalPage"
            class="pagination"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import { useRouter } from "vue-router";

const router = useRouter();
const abnormalRecords = ref([]);
const processingStatusMap = ref(new Map()); // 存储每个记录的处理状态

const searchForm = ref({
  abnormalType: '',
  status: '',
  pageNum:1,
  pageSize:4
});
const totalPage = ref(0);

// 计算过滤后的记录
const filteredRecords = computed(() => {
  let result = abnormalRecords.value;

  // 按异常类型过滤
  if (searchForm.value.abnormalType) {
    result = result.filter(record =>
      record.abnormalType.includes(searchForm.value.abnormalType)
    );
  }

  // 按处理状态过滤
  if (searchForm.value.status) {
    result = result.filter(record =>
      getProcessingStatus(record.abnormalId) === searchForm.value.status
    );
  }

  return result;
});

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '';
  const d = new Date(date);
  if (isNaN(d.getTime())) return '';

  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取处理状态
const getProcessingStatus = (abnormalId) => {
  return processingStatusMap.value.get(abnormalId) || 'pending';
};

// 加载异常记录
const loadAbnormalRecords = () => {
  axios.get(BASE_URL + `/api/abnormal-records/select`,{params:searchForm.value})
    .then((response) => {
      if (response.data.state === 2001) {
        abnormalRecords.value = response.data.data.list;
        totalPage.value = response.data.data.totalPage;

        // 获取每个记录的处理状态
        abnormalRecords.value.forEach(record => {
          loadProcessingStatus(record.abnormalId);
        });
      } else {
        ElMessage.error(response.data.msg);
      }
    })
    .catch(error => {
      ElMessage.error('加载异常记录失败: ' + (error.message || '网络错误'));
    });
};

// 加载处理状态
const loadProcessingStatus = (abnormalId) => {
  axios.get(BASE_URL + `/api/abnormal-records/processing/select/abnormal/${abnormalId}`)
    .then(response => {
      if (response.data.state === 2001) {
        processingStatusMap.value.set(abnormalId, response.data.data.status);
      } else {
        processingStatusMap.value.set(abnormalId, 'pending');
      }
    })
    .catch(() => {
      processingStatusMap.value.set(abnormalId, 'pending');
    });
};

// 重置搜索条件
const reset = () => {
  searchForm.value = {
    abnormalType: '',
    status: '',
    pageNum:1,
    pageSize:4
  };
  loadAbnormalRecords();
};

// 查看详情 - 修改路由名称为 abnormalProcess
const viewAbnormalRecord = (record) => {
  router.push({
    name: 'abnormalProcess',  // 关键修改：使用路由配置中定义的名称
    query: {
      abnormalId: record.abnormalId,
      abnormalType: record.abnormalType,
      reason: record.reason,
      createdAt: record.createdAt
    }
  });
};

onMounted(() => {
  loadAbnormalRecords();
});

const handleSizeChange = (pageSize) => {
  searchForm.value.pageSize = pageSize;
  loadAbnormalRecords();
}

const handleCurrentChange = (pageNum) => {
  searchForm.value.pageNum = pageNum;
  loadAbnormalRecords();
}
</script>

<style scoped>
.abnormal-record-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item__label) {
  font-weight: 500;
  margin-right: 8px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.abnormal-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.abnormal-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.abnormal-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.abnormal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.abnormal-id {
  font-weight: 600;
  color: #303133;
}

.status-tag {
  font-size: 12px;
}

.abnormal-content {
  padding: 15px 20px;
}

.abnormal-item {
  display: flex;
  margin-bottom: 12px;
}

.abnormal-item:last-child {
  margin-bottom: 0;
}

.abnormal-item label {
  width: 80px;
  font-weight: 500;
  color: #606266;
}

.abnormal-item span {
  flex: 1;
  color: #303133;
  word-break: break-all;
}

.abnormal-footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}

.no-data {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-start; /* 改为靠左对齐 */
}
</style>
